<template>
  <div class="el-main">
    <div>
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="起点">
              <el-input @change="load" v-model="form.startName" placeholder="起点"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="终点">
              <el-input @change="load" v-model="form.endName" placeholder="终点"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计算策略">
              <el-select v-model="form.policy" placeholder="计算策略">
                <el-option label="最少时间" value="LEAST_TIME"></el-option>
                <el-option label="最短距离" value="LEAST_DISTANCE"></el-option>
                <el-option label="避开高速" value="AVOID_HIGHWAYS"></el-option>
                <el-option label="实时路况" value="REAL_TRAFFIC"></el-option>
                <el-option label="预测路况" value="PREDICT_TRAFFIC"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-checkbox v-model="form.sp" @change="showP">显示路段地标</el-checkbox>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="选择起点">
              <el-select v-model="form.starts" placeholder="选择起点">
                <el-option
                    v-for="item in startOptions"
                    :key="item.key"
                    :label="item.name"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="选择终点">
              <el-select v-model="form.ends" placeholder="选择终点">
                <el-option
                    v-for="item in endOptions"
                    :key="item.key"
                    :label="item.name"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" @click="routeSearch">查询线路</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="关键字">
              <el-input v-model="form.keyword" placeholder="关键字搜索"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-button style="margin-left: 10px;" type="primary" @click="searchByKey">搜索</el-button>
            <el-button @click="searchByAddress">地址解析</el-button>
            <el-button @click="searchByLatLng">逆地址解析</el-button>
            <el-button @click="searchCityByName">城市搜索</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div id="container"></div>
    <div>
      <p v-for="(item,index) in content" :key="index" @click="renderStep(item)" class="step">
        <b>{{index + 1}}.</b>
        <span :style="item.style"></span>{{item.instructions}}
      </p>
    </div>
  </div>
</template>

<script>
  import { qqmap } from '../../components/map'
  import qq from 'qq'
  export default {
    name: "create",
    components: {},
    props: {},
    data() {
      return {
        map: null,
        form: {
          startName: '银科大厦',
          endName: '天坛公园',
          starts: 0,
          ends: 0,
          policy: 'LEAST_TIME',
          keyword: '越秀财富中心'
        },
        startOptions: [],
        endOptions: [],
        content: [],
        stepLine: null,
        directions_placemarks: [],
        start_marker: null,
        end_marker: null,
        route_lines: [],
        directions_labels: []
      }
    },
    mounted() {
      this.map = qqmap();
      this.load();
    },
    methods: {
      load() {
        var that = this;
        var drivingService = this.map.getDrivingService(function (response) {
          var starts = response.detail.start;
          var ends = response.detail.end;
          that.startOptions = [];
          that.endOptions = [];
          starts.forEach((start, index) => {
            that.startOptions.push({
              name: start.name,
              value: index,
              key: index,
              latLng: start.latLng
            });
          });
          ends.forEach((end, index) => {
            that.endOptions.push({
              name: end.name,
              value: index,
              key: index,
              latLng: end.latLng
            });
          });
        });
        drivingService.setLocation("北京");
        drivingService.setPolicy(qq.maps.DrivingPolicy[this.form.policy]);
        drivingService.search(this.form.startName, this.form.endName);
      },
      showP() {
        var that = this;
        if (this.form.sp) {
          for (var i = 0; i < that.directions_placemarks.length; i++) {
            var placemarks = that.directions_placemarks[i];
            for (var j = 0; j < placemarks.length; j++) {
              var placemark = placemarks[j];
              var label = new qq.maps.Label({
                map: that.map.map,
                position: placemark.latLng,
                content: placemark.name
              });
              that.directions_labels.push(label);
            }
          }
        } else {
          this.map.clearOverlays(that.directions_labels);
        }
      },
      renderStep(item) {
        var that = this;
        //clear overlays;
        that.stepLine && that.stepLine.setMap(null);
        //draw setp line
        that.stepLine = new qq.maps.Polyline(
          {
            path: item.path,
            strokeColor: '#ff0000',
            strokeWeight: 6,
            map: that.map.map,
            zIndex: 99
          }
        );
      },
      routeSearch() {
        var that = this;
        var startLatLng = this.startOptions[this.form.starts].latLng;
        var endLatLng = this.endOptions[this.form.ends].latLng;
        var directions_routes = [];
        that.directions_placemarks = [];
        that.content = [];
        that.map.clearOverlays();
        var drivingService = this.map.getDrivingService(function (response) {
          var start = response.detail.start,
            end = response.detail.end;
          var anchor = new qq.maps.Point(6, 6),
            size = new qq.maps.Size(24, 36),
            start_icon = new qq.maps.MarkerImage(
              'https://lbs.qq.com/javascript_v2/img/busmarker.png',
              size,
              new qq.maps.Point(0, 0),
              anchor
            ),
            end_icon = new qq.maps.MarkerImage(
              'https://lbs.qq.com/javascript_v2/img/busmarker.png',
              size,
              new qq.maps.Point(24, 0),
              anchor
            );
          that.start_marker && that.start_marker.setMap(null);
          that.end_marker && that.end_marker.setMap(null);
          that.map.clearOverlays(that.route_lines);
          that.start_marker = new qq.maps.Marker({
            icon: start_icon,
            position: start.latLng,
            map: that.map.map,
            zIndex: 1
          });
          that.end_marker = new qq.maps.Marker({
            icon: end_icon,
            position: end.latLng,
            map: that.map.map,
            zIndex: 1
          });
          directions_routes = response.detail.routes;
          for (var i = 0; i < directions_routes.length; i++) {
            var route = directions_routes[i],
              legs = route;
            that.map.map.fitBounds(response.detail.bounds);

            var steps = legs.steps;
            var polyline = new qq.maps.Polyline(
              {
                path: route.path,
                strokeColor: '#3893F9',
                strokeWeight: 6,
                map: that.map.map
              }
            );
            that.route_lines.push(polyline);
            for (var k = 0; k < steps.length; k++) {
              var step = steps[k];
              that.directions_placemarks.push(step.placemarks);
              //转向
              var turning = step.turning,
                img_position;

              switch (turning.text) {
                case '左转':
                  img_position = '0px 0px';
                  break;
                case '右转':
                  img_position = '-19px 0px';
                  break;
                case '直行':
                  img_position = '-38px 0px';
                  break;
                case '偏左转':
                case '靠左':
                  img_position = '-57px 0px';
                  break;
                case '偏右转':
                case '靠右':
                  img_position = '-76px 0px';
                  break;
                case '左转调头':
                  img_position = '-95px 0px';
                  break;
                default:
                  img_position = '';
                  break;
              }

              that.content.push({
                instructions: step.instructions,
                img_position: img_position,
                path: step.path,
                style: 'margin-bottom: -4px;display:inline-block;background:url(https://lbs.qq.com/javascript_v2/img/turning.png) no-repeat ' + img_position + ';width:19px;height:19px'
              })
            }
          }
        });
        drivingService.search(startLatLng, endLatLng);
      },
      searchByKey() {
        let keyword = this.form.keyword;
        var that = this;
        that.map.clearOverlays();
        let searchService = that.map.getSearchService(function (response) {
          let pois = response.detail.pois;
          let latlngBounds = new qq.maps.LatLngBounds();
          for (var i = 0, l = pois.length; i < l; i++) {
            let poi = pois[i];
            //扩展边界范围，用来包含搜索到的Poi点
            latlngBounds.extend(poi.latLng);
            (function (n) {
              var marker = new qq.maps.Marker({
                map: that.map.map
              });
              marker.setPosition(pois[n].latLng);
              marker.setTitle(i + 1);
              that.map.markers.push(marker);

              qq.maps.event.addListener(marker, 'click', function () {
                that.$message({
                  message: pois[n].name,
                  type: 'success'
                });
              });
            })(i);
          }
          //调整地图视野
          that.map.map.fitBounds(latlngBounds);
        });
        searchService.setLocation('北京');             //设置默认检索范围（默认为全国），类型可以是坐标或指定的城市名称。
        searchService.setPageIndex(0);         //设置检索的特定页数。
        searchService.setPageCapacity(10);
        searchService.search(keyword);
      },
      showResult(location, message) {
        var that = this;
        that.map.map.setCenter(location);
        var marker = new qq.maps.Marker({
          map: that.map.map,
          position: location
        });
        that.map.markers.push(marker);
        qq.maps.event.addListener(marker, 'click', function () {
          that.$message({
            message: message,
            type: 'success'
          });
        });
      },
      searchByAddress() {
        let keyword = this.form.keyword;
        var that = this;
        that.map.clearOverlays();
        that.map.getGeocoder(function (response) {
          that.showResult(response.detail.location, response.detail.address + '：' + response.detail.location);
        }).getLocation(keyword);
      },
      searchByLatLng() {
        let keyword = this.form.keyword;
        var that = this;
        that.map.clearOverlays();

        var latlngStr = keyword.split(",", 2);
        var lat = parseFloat(latlngStr[0]);
        var lng = parseFloat(latlngStr[1]);
        var latLng = new qq.maps.LatLng(lat, lng);
        that.map.getGeocoder(function (response) {
          that.showResult(response.detail.location, response.detail.address + '：' + response.detail.location);
        }).getAddress(latLng);
      },
      searchCityByName() {
        let keyword = this.form.keyword;
        let that = this;
        that.map.clearOverlays();

        that.map.getCityService(function (response) {
          that.showResult(response.detail.latLng, response.detail.detail + '：' + response.detail.latLng);
        }).searchCityByName(keyword);
      }
    }
  }
</script>

<style scoped>
  #container {
    min-width: 600px;
    min-height: 300px;
  }

  .step {
    background: #eee;
    margin: 5px 0px;
    cursor: pointer;
  }

  .step:hover {
    background: #fff;
  }
</style>
